package com.wangyi.fightimg.moduls.category;

import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ddrx.refresh.SwipeRefresh;
import com.ddrx.refresh.SwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.wangyi.fightimg.application.MyApplication;
import com.wangyi.fightimg.R;
import com.wangyi.fightimg.base.BaseFragment;
import com.wangyi.fightimg.moduls.MainActivity;
import com.wangyi.fightimg.moduls.main.MainFragmentAdapter;
import com.wangyi.fightimg.moduls.main.MainFragmentBean;
import com.wangyi.fightimg.utils.ConstantUtil;
import com.wangyi.fightimg.utils.http.NetResponse;
import com.wangyi.fightimg.utils.http.OkHttpUtil;
import com.wangyi.fightimg.utils.http.ServiceUrl;
import com.wangyi.fightimg.utils.http.download.DownloadImg;
import com.wangyi.fightimg.utils.http.download.DownloadListener;
import com.wangyi.fightimg.widget.sharepopup.SharePopupWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;

/**
 * @author wangYi
 *         分类页面
 */

public class CategoryFragment extends BaseFragment implements View.OnClickListener, MainFragmentAdapter.OnItemClickListener {

    @Bind(R.id.tv_left)
    TextView tvLeft;// 标题栏左侧内容
    @Bind(R.id.rv_imgs)
    RecyclerView rvImgs;// 图片列表
    @Bind(R.id.ll_category)
    LinearLayout llCategory;// 分类列表父布局
    @Bind(R.id.lv_category)
    ListView lvCategory;// 分类列表
    @Bind(R.id.dl_category_root)
    DrawerLayout dlCategoryRoot;// 抽屉
    @Bind(R.id.srl_refresh)
    SwipeRefreshLayout srlRefresh;// 刷新

    private List<MainFragmentBean> imgBeanList = new ArrayList<>();// 图片列表项集合
    private List<CategoryBean> categoryBeanList = new ArrayList<>();// 分类列表项数据集合
    private CategoryAdapter categoryAdapter;// 分类列表适配器
    private MainFragmentAdapter imageAdapter;// 图片列表适配器
    private int selectedIndext;// 当前选中种类
    private int categoryId;// 当前分类ID
    private int currentPage;// 当前图片列表页面页数
    private boolean isShowing;//  分类列表是否显示
    private boolean hasNextPage;// 是否存在下一页
    private SharePopupWindow sharePopupWindow;// 分享弹框
    private String imgUri;// 分享图片本地地址
    private IWXAPI api;// 微信api
    public IUiListener iUiListener;// QQ分享回调监听

    @Override
    protected int addLayout() {
        return R.layout.fragment_category;
    }

    @Override
    protected void addListener() {
        // 分类列表点击事件
        lvCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectedIndext != position) {
                    categoryBeanList.get(selectedIndext).setSelected(false);
                    categoryBeanList.get(position).setSelected(true);
                    selectedIndext = position;
                    categoryAdapter.notifyDataSetChanged();
                    dlCategoryRoot.closeDrawer(llCategory);

                    categoryId = categoryBeanList.get(position).getId();
                    currentPage = 1;
                    hasNextPage = false;
                    getImgFromServer(categoryId, currentPage, true, true);
                }
            }
        });
        // 抽屉展示隐藏监听
        dlCategoryRoot.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                isShowing = true;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isShowing = false;
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        // 上拉加载监听
        srlRefresh.setOnPullUpRefreshListener(new SwipeRefreshLayout.OnPullUpRefreshListener() {
            @Override
            public void onPullUpRefresh() {
                if (hasNextPage) {
                    getImgFromServer(categoryId, ++currentPage, false, false);
                } else {
                    srlRefresh.setPullUpRefreshing(false);
                }
            }
        });

        // 下拉刷新监听
        srlRefresh.setOnRefreshListener(new SwipeRefresh.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                hasNextPage = false;
                getImgFromServer(categoryId, currentPage, true, false);
            }
        });
        tvLeft.setOnClickListener(this);
    }

    @Override
    protected void findView() {
        ButterKnife.bind(this, rootView);
        tvLeft.setText("分类");
    }

    @Override
    protected void initializedPage() {
        iUiListener = ((MainActivity) getActivity()).iUiListener;
        api = ((MyApplication) context.getApplicationContext()).getApi();
        selectedIndext = 0;
        currentPage = 1;
        hasNextPage = false;
        srlRefresh.setColorSchemeResources(R.color.LIGHT_BLUE, R.color.GREEN, R.color.BLUE, R.color.RED);
        srlRefresh.setMode(SwipeRefresh.Mode.BOTH);

        categoryAdapter = new CategoryAdapter(context, categoryBeanList);
        lvCategory.setAdapter(categoryAdapter);

        StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);

        rvImgs.setLayoutManager(gridLayoutManager);
        rvImgs.getItemAnimator().setChangeDuration(0);
        rvImgs.getItemAnimator().setAddDuration(0);
        rvImgs.getItemAnimator().setChangeDuration(0);
        rvImgs.getItemAnimator().setMoveDuration(0);
        rvImgs.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rvImgs.getItemAnimator()).setSupportsChangeAnimations(false);

        imageAdapter = new MainFragmentAdapter(context, imgBeanList);
        imageAdapter.setCheckChangeListtener(this);
        rvImgs.setAdapter(imageAdapter);
        getCategoryFromServer();
    }

    /**
     * 从服务器获取分类数据
     */
    private void getCategoryFromServer() {
        Map<String, String> params = new HashMap<>();
        OkHttpUtil.getInstance(context).get(ServiceUrl.CATEGORY_LIST, params, false, new NetResponse<ResponseBody>() {
            @Override
            public void succeed(JSONObject success) {
                Gson gson = new Gson();
                List<CategoryBean> data = gson.fromJson(success.optString("result"), new TypeToken<List<CategoryBean>>() {
                }.getType());
                if (data != null && data.size() > 0) {
                    data.get(0).setSelected(true);
                    categoryBeanList.addAll(data);
                    categoryAdapter.notifyDataSetChanged();
                    categoryId = categoryBeanList.get(0).getId();
                    getImgFromServer(categoryId, currentPage, true, false);
                }
            }

            @Override
            public void fail(String error) {

            }
        });
    }

    /**
     * 从服务器获取分类图片数据
     */
    private void getImgFromServer(int catalogId, int pageNum, final boolean isRefresh, boolean showDialog) {
        Map<String, String> params = new HashMap<>();
        params.put("catalogId", "" + catalogId);
        params.put("pageNum", "" + pageNum);
        params.put("pageSize", "" + 20);
        OkHttpUtil.getInstance(context).get(ServiceUrl.IMG_LIST, params, showDialog, new NetResponse<ResponseBody>() {
            @Override
            public void succeed(JSONObject success) {
                if (isRefresh) {
                    imgBeanList.clear();
                }
                try {
                    JSONObject jsonObject = success.getJSONObject("result");
                    hasNextPage = jsonObject.optBoolean("hasNextPage");
                    Gson gson = new Gson();
                    List<MainFragmentBean> data = gson.fromJson(jsonObject.optString("list"), new TypeToken<List<MainFragmentBean>>() {
                    }.getType());
                    if (data != null) {
                        imgBeanList.addAll(data);
                    }
                    if (isRefresh) {
                        imageAdapter.notifyDataSetChanged();
                    } else {
                        imageAdapter.notifyItemRangeInserted(imgBeanList.size() - data.size(), data.size());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    if (srlRefresh != null) {
                        if (srlRefresh.isRefreshing()) {
                            srlRefresh.setRefreshing(false);
                        } else if (srlRefresh.ismRefreshingForBottom()) {
                            srlRefresh.setPullUpRefreshing(false);
                        }
                    }
                }
            }

            @Override
            public void fail(String error) {
                if (srlRefresh != null) {
                    if (srlRefresh.isRefreshing()) {
                        srlRefresh.setRefreshing(false);
                    } else if (srlRefresh.ismRefreshingForBottom()) {
                        srlRefresh.setPullUpRefreshing(false);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                if (isShowing) {
                    dlCategoryRoot.closeDrawer(llCategory);
                } else {
                    dlCategoryRoot.openDrawer(llCategory);
                }
                break;
            default:
                break;

        }
    }


    @Override
    public void setOnClickListener(View view, int position) {
        if (view.getId() == R.id.tv_category) {
            imgBeanList.get(position).setCheck(true);
            imgBeanList.get(position).setCount(imgBeanList.get(position).getCount() + 1);
            imageAdapter.notifyItemChanged(position, "1");
        } else if (view.getId() == R.id.iv_share) {
            String imgUrl = (String) view.getTag();
            imgUri = ConstantUtil.imgUriBas + "/" + imgUrl.split("/")[imgUrl.split("/").length - 1];
            File fileDir = new File(ConstantUtil.imgUriBas);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            DownloadImg.getInstance(context).startDownload(imgUrl, new DownloadListener() {
                @Override
                public void onSuccess() {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            showPopupWindow();
                        }
                    });
                }

                @Override
                public void onFaile(String error) {

                }
            });


        }
    }

    /**
     * 展示分享弹框
     */
    private void showPopupWindow() {
        final WindowManager.LayoutParams layoutParams = getActivity().getWindow().getAttributes();
        layoutParams.alpha = 0.3f;
        getActivity().getWindow().setAttributes(layoutParams);
        if (sharePopupWindow == null) {
            sharePopupWindow = new SharePopupWindow(context, api, iUiListener);
            sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    layoutParams.alpha = 1.0f;
                    getActivity().getWindow().setAttributes(layoutParams);
                }
            });
        }
        sharePopupWindow.setImgUri(imgUri);
        sharePopupWindow.showAtLocation(tvLeft, Gravity.BOTTOM, 0, 0);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
